package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.omg.CORBA.TIMEOUT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信验证码
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //调用工具类发送短信
        //SMSUtils.sendSms(phone,code);
        log.info("code={}",code);
        //将生成的验证码保存到 session 中
        //session.setAttribute("code",code);
        //将生成的验证码保存到 redis 中,设置过期时间
        redisTemplate.opsForValue().set("code_"+phone,code,120,TimeUnit.SECONDS);
        return R.success("手机验证码短信发送成功");
    }

    /**
     * 移动端用户登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        //获取手机号
        String phone = map.get("phone");
        //获取验证码
        String code1 = map.get("code");
        //从 session中获取保存的验证码
        //String code2 = (String) session.getAttribute("code");
        //从 redis中获取保存的验证码
        String code2= (String) redisTemplate.opsForValue().get("code_"+phone);
        //对比验证码
        if (!StringUtils.equals(code1,code2)){
            return R.error("验证码输入错误");
        }
         //判断手机号是否为新用户
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        User user= userService.getOne(queryWrapper);
        if (user==null){
            //是新用户,注册
            user = new User();
            user.setStatus(1);
            user.setPhone(phone);
            userService.save(user);
        }
        //将用户id存入 session 中
        session.setAttribute("user",user.getId());

        //销毁验证码
        redisTemplate.delete("code_"+phone);

        return R.success(user);
    }
}
